<template>
  <div>
    <el-form label-width="90px" label-position="top">
      <el-form-item label="表单名称">
        <el-input clearable v-model.trim="form.title" @blur="handelValidateComponentTitle" />
      </el-form-item>
      <component :is="showComponents" v-model="form.props" />
    </el-form>
  </div>
</template>

<script setup>
import { computed, getCurrentInstance } from "vue";
import useFlowStore from "@/store/modules/gkflow.js";
import TextInput from "./configComponents/TextInputConfig.vue";
import TextareaInput from "./configComponents/TextareaInputConfig.vue";
import MultipleSelect from "./configComponents/SelectInputConfig.vue";
import SelectInput from "./configComponents/SelectInputConfig.vue";
import DateTime from "./configComponents/DateTimeConfig.vue";
import FileUpload from "./configComponents/FileUploadConfig.vue";

const { proxy } = getCurrentInstance();

const flowStore = useFlowStore();
const form = computed(() => {
  return flowStore.selectFormItem;
});
const forms = computed(() => {
  return flowStore.design?.formItems || [];
});
const showComponents = computed(() => {
  const cmps = {
    TextInput: TextInput,
    TextareaInput: TextareaInput,
    MultipleSelect: MultipleSelect,
    SelectInput: SelectInput,
    DateTime: DateTime,
    FileUpload: FileUpload
  };
  return cmps[form.value.name];
});

const handelInsideFormTitle = formItem => {
  return new Promise((resolve, reject) => {
    try {
      const filterData = forms.value?.filter(item => item.title === formItem.title) || [];
      resolve(filterData.length > 1);
    } catch (err) {
      reject(err);
    }
  });
};
const handelValidateComponentTitle = async () => {
  const formItemData = form.value;
  if (!formItemData.title) return;
  const insideValidate = await handelInsideFormTitle(formItemData);
  if (insideValidate) proxy.$modal.msgError("同一分组下表单名称不允许重复");
};
</script>
